<template>
  <div class="distributor-invoice-should-open">
    <!-- 搜索 -->
    <div class="header">
      <m-search
        ref="SearchForm"
        label-width="66px"
        :data="SEARCH_DATA"
        @searchForm="onSearch"
        @resetForm="onReset"
      />
    </div>
    <!-- tab状态 -->
    <div class="tab">
      <tabs
        :tabs-arr="TAB_ARR"
        :active-index="auditStatus"
        @returnIndex="onHandletabs"
      >
        <el-button
          :disabled="!table.dataList.length"
          type="primary"
          @click="onDownload"
        >
          <m-iconfont
            classify="m-pc-public"
            icon="m-pc-public_daocsj"
            size="14"
          /><span>导出数据</span>
        </el-button>
        <el-button
          :disabled="!table.dataList.length"
          type="primary"
          @click="onDownloadData"
        >
          <m-iconfont
            classify="m-pc-public"
            icon="m-pc-public_xiaz"
            size="14"
          /><span>下载数据</span>
        </el-button>
        <!-- 本期废弃 -->
        <!-- <el-button type="primary" @click="onBilling(1)">
          <m-iconfont
            classify="m-pc-public"
            icon="m-pc-public_yijkp"
            size="14"
          /><span>一键开票</span>
        </el-button> -->
      </tabs>
    </div>
    <!-- 列表 -->
    <m-editable
      v-loading="table.tableLoading"
      :empty-type="table.resultType"
      :data="table.dataList"
      :columns="COLUMNS_TABLE"
      height="400"
      @selection-change="onHandleSelectionChange"
    >
      <template slot="default-action" slot-scope="scope">
        <el-button
          :disabled="scope.row.billingStatus !== '1'"
          type="primary"
          plain
          size="mini"
          @click.stop="onBilling(0, scope.row)"
          >提交开票</el-button
        >
        <el-button
          :disabled="scope.row.billingStatus !== '4'"
          type="primary"
          plain
          size="mini"
          @click.stop="onCancelBilling(scope.row)"
          >取消</el-button
        >
        <el-button
          type="primary"
          plain
          size="mini"
          @click.stop="onDetails(scope.row)"
          >查看</el-button
        >
      </template>
    </m-editable>
    <!-- 分页模块 -->
    <div v-if="table.dataList.length > 0" class="footer">
      <el-pagination
        class="pageBox"
        align="right"
        :page-size="page.size"
        :current-page="page.curPage"
        :total="page.total"
        :layout="page.PAGINATION_LAYOUT"
        :page-sizes="page.PAGE_NUMBER"
        @size-change="onPageSizeChange"
        @current-change="onPageCurrentChange"
      />
    </div>
    <!-- 添加操作 -->
    <m-dialog
      class="popup__m-dialog"
      title="开具发票"
      width="middle"
      :confirm-loading="billingForm.confirmLoading"
      :visible.sync="billingForm.showBillingForm"
      :before-close="onHandleClose"
      @refuse="onHandleClose"
      @confirm="onSubmit"
      @closeBtn="onHandleClose"
    >
      <template #content>
        <el-form
          ref="billingForm"
          :model="billingForm"
          :rules="rulesBillingForm"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="发票类型" prop="invoiceType">
            <el-select v-model="billingForm.invoiceType" placeholder="请选择">
              <el-option
                v-for="(item, index) in INVOICE_TYPE"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否带清单" prop="isList">
            <el-select v-model="billingForm.isList" placeholder="请选择">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </m-dialog>
  </div>
</template>
<script>
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common';
import tabs from '@pc/m-components/m-tabs/index.vue';
import {
  distributorShouldOpenInvoiceList,
  distributorShouldOpenInvoiceStatistics,
  distributorShouldOpenInvoicebatchBilling,
  exportShouldOpenInvoice,
  exportShouldOpenInvoiceData,
  cancelBillingApply,
} from '@api/hossyn-order-center';
import { $loadFileSimply } from '@pc/const/loadFileOps';
import { fileDownload } from '@pc/const/utils';
import { formatDate } from '@const/filter.js';
import * as CONSTS from './const';

export default {
  components: {
    tabs,
  },
  data() {
    return {
      ...CONSTS,
      auditStatus: 0,
      table: {
        searchData: {},
        tableLoading: false,
        resultType: 0,
        dataList: [],
        selectionChangeList: [],
      },
      page: {
        PAGE_NUMBER, // 页码数组
        PAGINATION_LAYOUT, // 页码功能布局
        curPage: 1,
        pageSize: PAGE_NUMBER[0],
        total: 0,
      },
      billingForm: {
        showBillingForm: false,
        confirmLoading: false,
        invoiceType: '',
        isList: '',
      },
      rulesBillingForm: {
        invoiceType: [
          { required: true, message: '请选择发票类型', trigger: 'change' },
        ],
        isList: [
          { required: true, message: '请选择是否带清单', trigger: 'change' },
        ],
      },
    };
  },
  mounted() {
    this.getDataList();
    this.getInvoiceStatistics();
  },
  methods: {
    onCancelBilling(row) {
      this.$mdialog({
        type: 'warning',
        message: '是否确认取消？',
        'confirm-text': '确定',
        'refuse-text': '取消',
      })
        .then(() => {
          this.$axios({
            url: cancelBillingApply,
            method: 'post',
            data: {
              settleMainOrderId: row.settleOrderMainId,
            },
          }).then((res) => {
            if (res.data.code === '0') {
              this.getDataList();
              this.getInvoiceStatistics();
              this.$message({
                type: 'success',
                message: '已取消!',
              });
            }
          });
        })
        .catch(() => {});
    },
    // 下载数据
    onDownloadData() {
      const params = {
        url: exportShouldOpenInvoiceData,
        method: 'post',
        data: {
          ...this.table.searchData,
          billingStatus: this.TAB_ARR[this.auditStatus].val,
        },
      };
      const timeStr = formatDate(new Date(), 'YYYYMMDDHHmmss');
      $loadFileSimply(params).then((res) => {
        fileDownload(res, `结算明细查询数据导出${timeStr}.xls`);
      });
    },
    onDownload() {
      const params = {
        url: exportShouldOpenInvoice,
        method: 'post',
        data: {
          ...this.table.searchData,
          billingStatus: this.TAB_ARR[this.auditStatus].val,
        },
      };
      const timeStr = formatDate(new Date(), 'YYYYMMDDHHmmss');
      $loadFileSimply(params).then((res) => {
        fileDownload(res, `查询导出${timeStr}.xls`);
      });
    },
    // 获取统计小红点
    getInvoiceStatistics() {
      this.$axios({
        url: distributorShouldOpenInvoiceStatistics,
        method: 'post',
      }).then((res) => {
        const statisticsArr = res.data.payload || [];
        statisticsArr.forEach((it) => {
          if (it.status === 1) {
            this.TAB_ARR[1].badge = it.num || '';
          }
          if (it.status === 4) {
            this.TAB_ARR[2].badge = it.num || '';
          }
        });
      });
    },
    // 详情
    onDetails(row) {
      this.$router.push({
        path: '/distributorSide/invoice-management/invoice-details',
        query: {
          settleOrderId: row.sendInvoiceId,
          settleOrderCode: row.settleOrderMainCode,
          settleOrderMainId: row.settleOrderMainId,
        },
      });
      // const routeUrl = this.$router.resolve({
      //   path: '/distributorSide/invoice-management/invoice-details',
      //   query: {
      //     settleOrderId: row.sendInvoiceId,
      //     settleOrderCode: row.settleOrderMainCode,
      //     settleOrderMainId: row.settleOrderMainId,
      //   },
      // });
      // window.open(routeUrl.href, '_blank');
    },
    // 勾选的数据
    onHandleSelectionChange(val) {
      this.table.selectionChangeList = val;
    },
    // 获取列表数据
    getDataList(flage) {
      this.table.tableLoading = true;
      this.$axios({
        url: distributorShouldOpenInvoiceList,
        method: 'post',
        data: {
          ...this.table.searchData,
          billingStatus: this.TAB_ARR[this.auditStatus].val,
          page: this.page.curPage,
          pageSize: this.page.pageSize,
        },
      })
        .then((res) => {
          this.table.dataList = res.data.payload.content || [];
          this.page.total = res.data.payload.totalElements || 0;
          if (flage) {
            this.table.resultType = 1;
          } else {
            this.table.resultType = 0;
          }
        })
        .finally(() => {
          this.table.tableLoading = false;
        });
    },
    // 开票的提交
    onSubmit() {
      this.$refs.billingForm.validate((valid) => {
        if (valid) {
          this.$axios({
            url: distributorShouldOpenInvoicebatchBilling,
            method: 'post',
            data: {
              invoiceType: this.billingForm.invoiceType,
              isList: Number(this.billingForm.isList),

              settleMainOrderIdList: this.table.selectionChangeList.map(
                (item) => {
                  const idList = item.settleOrderMainId.toString();
                  return idList;
                }
              ),
            },
          })
            .then((res) => {
              if (res.data.code === '0') {
                this.$message({
                  type: 'success',
                  message: '提交成功!',
                });
                this.onHandleClose();
                this.getDataList();
                this.getInvoiceStatistics();
              }
            })
            .finally(() => {
              this.table.tableLoading = false;
            });
        }
      });
    },
    // 上传发票的取消、关闭弹框
    onHandleClose() {
      this.$refs.billingForm.resetFields();
      this.billingForm.showBillingForm = false;
    },
    // 上传发票
    onBilling(type, item) {
      if (type === 1) {
        // 多个上传
        if (this.table.selectionChangeList.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择需要上传发票的结算单!',
          });
          return;
        }
      } else {
        // 单个上传
        this.table.selectionChangeList = [item];
      }
      this.billingForm.showBillingForm = true;
    },
    // 搜索
    onSearch(condition) {
      this.page.curPage = 1;
      this.table.searchData = condition;
      this.getDataList('search');
      this.getInvoiceStatistics();
    },
    // 重置
    onReset(condition) {
      this.page.curPage = 1;
      this.table.searchData = condition;
      this.getDataList();
      this.getInvoiceStatistics();
    },
    // tab切换事件
    onHandletabs(val) {
      this.page.curPage = 1;
      this.auditStatus = val;
      this.getDataList();
      this.getInvoiceStatistics();
    },
    // 点击分页事件
    onPageSizeChange(size) {
      this.page.pageSize = size;
      this.getDataList();
      this.getInvoiceStatistics();
    },
    onPageCurrentChange(curPage) {
      this.page.curPage = curPage;
      this.getDataList();
      this.getInvoiceStatistics();
    },
  },
};
</script>
<style lang="less">
.distributor-invoice-should-open {
  margin: 0 20px 10px 20px !important;
  display: flex;
  flex-direction: column;
  .tab {
    margin-bottom: 20px;
  }
  .footer {
    padding: 7px 26px 6px 0;
    border: 1px solid @cutOffRuleColor;
    border-top: none;
    border-radius: 0 0 3px 3px;
  }
  .popup__m-dialog {
    .el-select {
      width: 100%;
    }
  }
}
</style>
